﻿using Castle.DynamicProxy;
using System;

namespace Marmat.Common.Http
{

    /// <summary>
    /// HttpApi代理工厂类。
    /// </summary>
    public sealed class HttpFactory
    {

        static readonly ProxyGenerator generator = new ProxyGenerator();
        static HttpApiConfig httpApiConfig = new HttpApiConfig();

        /// <summary>
        /// 创建Http接口代理，
        /// </summary>
        /// <typeparam name="T">需要创建的接口类型</typeparam>
        /// <returns></returns>
        public static T Create<T>() where T : class
        {
            HttpApiInterceptor interceptor = new HttpApiInterceptor(httpApiConfig, typeof(T));
            //使用【代理类生成器】创建T对象，而不是使用new关键字来实例化 
            return generator.CreateInterfaceProxyWithoutTarget<T>(interceptor);
        }

        /// <summary>
        /// 创建Http接口代理。
        /// </summary>
        /// <typeparam name="T">需要创建的接口类型</typeparam>
        /// <param name="action"></param>
        /// <returns></returns>
        public static T Create<T>(Action<HttpApiConfig> action) where T : class
        {
            HttpApiConfig config = new HttpApiConfig();
            action?.Invoke(config);
            HttpApiInterceptor interceptor = new HttpApiInterceptor(config, typeof(T));
            //使用【代理类生成器】创建T对象，而不是使用new关键字来实例化 
            return generator.CreateInterfaceProxyWithoutTarget<T>(interceptor);
        }

        /// <summary>
        /// 设置HttpApi的默认配置。
        /// </summary>
        /// <param name="action"></param>
        public static void ConfigureHttpApiConfig(Action<HttpApiConfig> action)
        {
            httpApiConfig = new HttpApiConfig();
            action?.Invoke(httpApiConfig);
        }
    }
}
